var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('myDB', ['contactList']);
app.use(express.static (__dirname + "/public"));
var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.get ('/contactList', function (req, res) {
	/* body... */
	console.log('I received a GET request');
	// person1 = {
	// 	name: 'tim',
	// 	email: 'tim@email.com',
	// 	number: '111111'
	// };
	// persion2 = {
	// 	name: 'Emaily',
	// 	email: 'Emaily@email.com',
	// 	number: '2222'
	// };
	// preson3 = {
	// 	name: 'Jhone',
	// 	email: 'Jhone@email.com',
	// 	number: '3333'
	// };
	// var contactList = [person1, persion2, preson3];
	// 
	db.contactList.find(function (err, docs) {
		console.log(docs);
		res.json(docs);
		/* body... */
	});
	// res.json(docs);
});
app.post ('/contactList', function (req, res) {
	/* body... */
	console.log('this is a post request');
	console.log(req.body);
	db.contactList.insert(req.body, function (err, doc) {
		/* body... */
		res.json(doc);
	});
});
app.delete('/contactList/:id', function (req, res) {
	/* body... */
	var id = req.params.id;
	console.log(id);
	db.contactList.remove({_id: mongojs.ObjectId(id)}, function (err, doc) {
		/* body... */
		res.json(doc);
	});
});
app.get('/contactList/:id', function (req, res) {
	/* body... */
	var id = req.params.id;
	console.log(id);
	db.contactList.findOne({_id:mongojs.ObjectId(id)}, function (err, doc) {
		/* body... */
		res.json(doc);
	});
});
app.put('/contactList/:id', function (req, res) {
	/* body... */
	var id = req.params.id;
	console.log(req.body.name);
	db.contactList.findAndModify(
	{
		query:{_id:mongojs.ObjectId(id)},
	 	update:{ $set:{name: req.body.name, email:req.body.email, number:req.body.number}}, 
		new:true
	}, function (err, doc) {
			/* body... */
			res.json(doc);
		}
	);
});
app.listen(3000);
console.log('server running on port 3000');